<template>
  <view class="chat-page">
    <!-- 头部导航 -->
    <view class="header">
      <text class="page-title">小怡助手</text>
      <view class="header-right">
        <text class="iconfont reset-btn" @tap="resetChat">&#xe600;</text>
      </view>
    </view>
    
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-container" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
      upper-threshold="50"
      ref="chatScroll"
    >
      <!-- 欢迎消息 -->
      <view class="welcome-section" v-if="messages.length === 0">
        <image class="ai-logo" src="../../static/ai助理.jpg" mode="aspectFit"></image>
        <text class="welcome-title">小怡健康助手</text>
        <text class="welcome-desc">您的智能健康管家，随时为您提供专业服务</text>
        
        <!-- 推荐问题 -->
        <view class="suggest-questions">
          <view 
            class="question-item" 
            v-for="(question, index) in suggestQuestions" 
            :key="index"
            @tap="sendSuggestQuestion(question)"
          >
            <text class="question-text">{{question}}</text>
          </view>
        </view>
      </view>
      
      <!-- 聊天消息列表 -->
      <view class="message-list" v-else>
        <view 
          class="message-item" 
          :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
          v-for="(message, index) in messages" 
          :key="index"
        >
          <!-- 用户头像 -->
          <image 
            v-if="message.type === 'user'" 
            class="avatar user-avatar" 
            :src="userAvatar" 
            mode="aspectFill"
            @error="handleUserAvatarError"
          ></image>
          
          <!-- AI头像 -->
          <image 
            v-else 
            class="avatar ai-avatar" 
            src="../../static/ai助理.jpg" 
            mode="aspectFill"
          ></image>
          
          <!-- 消息内容 -->
          <view class="message-bubble" :class="{'user-bubble': message.type === 'user', 'ai-bubble': message.type === 'ai'}">
            <text class="message-text">{{message.content}}</text>
            <view class="message-time">{{message.time}}</view>
          </view>
        </view>
        
        <!-- 正在输入提示 -->
        <view class="ai-typing" v-if="isAiTyping">
          <image class="avatar ai-avatar" src="../../static/ai助理.jpg" mode="aspectFill"></image>
          <view class="typing-bubble">
            <view class="typing-dots">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <textarea 
          class="message-input" 
          v-model="inputMessage" 
          placeholder="输入您的问题..." 
          confirm-type="send"
          :disable-default-padding="true"
          :cursor-spacing="10"
          :show-confirm-bar="false"
          :auto-height="true"
          :maxlength="-1"
          @confirm="sendMessage"
          @focus="handleInputFocus"
          @blur="handleInputBlur"
        />
        <view class="send-btn" :class="{'active': inputMessage.trim().length > 0}" @tap="sendMessage">
          <text class="iconfont send-icon">&#xe653;</text>
        </view>
      </view>
      
      <!-- 功能按钮区 -->
      <view class="function-bar">
        <view class="function-item" @tap="switchToVoice">
          <text class="iconfont">&#xe6dc;</text>
        </view>
        <view class="function-item" @tap="chooseImage">
          <text class="iconfont">&#xe67c;</text>
        </view>
        <view class="function-item" @tap="showHealthMenu">
          <text class="iconfont">&#xe607;</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { getUserAvatar } from '../../api/user.js';
import useAuthCheck from '../../utils/authCheck';

// 引入权限校验
const { checkAuth } = useAuthCheck();

// 聊天相关数据
const messages = ref([]);
const inputMessage = ref('');
const isAiTyping = ref(false);
const scrollTop = ref(0);
const userAvatar = ref('../../image/R.jpg');
const chatScroll = ref(null);

// 推荐问题
const suggestQuestions = ref([
  '有什么方法可以改善失眠问题？',
  '如何缓解膝关节疼痛？',
  '老年人日常饮食应该注意什么？',
  '如何正确测量血压？'
]);

// 页面加载时检查登录状态和自动发送欢迎消息
onMounted(() => {
  // 检查登录状态
  if (checkAuth()) {
    // 已登录，加载头像
    loadUserAvatar();
  }
  
  // 自动发送欢迎消息
  nextTick(() => {
    autoSendWelcomeMessage();
  });
});

// 自动发送欢迎消息
const autoSendWelcomeMessage = () => {
  // 添加AI消息
  messages.value.push({
    type: 'ai',
    content: '您好！我是您的专属健康助手小怡，很高兴为您服务。请问有什么可以帮您的吗？',
    time: formatTime(new Date())
  });
  
  // 滚动到底部
  scrollToBottom();
};

// 加载用户头像
const loadUserAvatar = () => {
  getUserAvatar()
    .then(url => {
      userAvatar.value = url;
    })
    .catch(error => {
      console.error('获取头像失败:', error);
      userAvatar.value = '../../image/R.jpg';
    });
};

// 处理用户头像加载错误
const handleUserAvatarError = () => {
  console.log('头像加载失败，使用默认头像');
  userAvatar.value = '../../image/R.jpg';
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return;
  
  // 添加用户消息
  const userMessage = {
    type: 'user',
    content: inputMessage.value,
    time: formatTime(new Date())
  };
  
  messages.value.push(userMessage);
  
  // 清空输入框
  const sentMessage = inputMessage.value;
  inputMessage.value = '';
  
  // 显示AI正在输入
  isAiTyping.value = true;
  
  // 滚动到底部
  scrollToBottom();
  
  // 模拟AI回复
  simulateAiResponse(sentMessage);
};

// 发送推荐问题
const sendSuggestQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 模拟AI回复
const simulateAiResponse = (question) => {
  // 模拟网络延迟
  setTimeout(() => {
    // 根据问题生成回复
    let aiResponse = '';
    
    if (question.includes('失眠')) {
      aiResponse = '改善失眠的方法有：\n1. 保持规律的作息时间\n2. 睡前避免使用电子设备\n3. 创造舒适的睡眠环境\n4. 睡前可以做些轻松的活动，如深呼吸、听轻音乐\n5. 避免睡前饮用咖啡、茶等含咖啡因的饮料';
    } else if (question.includes('膝关节')) {
      aiResponse = '缓解膝关节疼痛可以：\n1. 适当休息，避免长时间站立或行走\n2. 局部热敷或冷敷\n3. 进行膝关节周围肌肉的锻炼，增强支撑力\n4. 控制体重，减轻膝关节负担\n5. 穿着合适的鞋子，可考虑使用护膝\n\n如果疼痛严重，建议及时就医';
    } else if (question.includes('饮食')) {
      aiResponse = '老年人日常饮食应注意：\n1. 食物多样化，保证营养均衡\n2. 适量摄入优质蛋白质，如鱼类、豆制品、蛋类\n3. 多吃新鲜蔬果，补充维生素和膳食纤维\n4. 少盐少油，控制脂肪摄入\n5. 少食多餐，避免过饱\n6. 保证充足的水分摄入\n7. 根据个人健康状况调整饮食内容';
    } else if (question.includes('血压')) {
      aiResponse = '正确测量血压的步骤：\n1. 测量前休息5-10分钟\n2. 取坐位，手臂与心脏保持同一水平\n3. 袖带绑在上臂，下缘距肘窝2-3厘米\n4. 测量时保持安静，不说话\n5. 最好在同一时间段测量，建议早晚各测一次\n6. 连续测量两次，间隔1-2分钟，取平均值\n\n正常血压范围：收缩压<140mmHg，舒张压<90mmHg';
    } else {
      aiResponse = '我是您的小怡健康助手，可以为您提供健康咨询、用药指导、饮食建议和康复训练等方面的信息。请详细描述您的问题，我会尽力为您解答。';
    }
    
    // 添加AI回复
    isAiTyping.value = false;
    messages.value.push({
      type: 'ai',
      content: aiResponse,
      time: formatTime(new Date())
    });
    
    // 滚动到底部
    scrollToBottom();
  }, 1000 + Math.random() * 1000); // 随机1-2秒延迟
};

// 格式化时间
const formatTime = (date) => {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    // 计算所有消息的高度
    const query = uni.createSelectorQuery().in(this);
    query.select('.message-list').boundingClientRect(data => {
      if (data) {
        scrollTop.value = data.height * 2; // 确保滚动到底部
      }
    }).exec();
  });
};

// 加载更多消息
const loadMoreMessages = () => {
  // 实际应用中可从服务器加载历史消息
  console.log('加载更多消息');
};

// 重置聊天
const resetChat = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空当前对话吗？',
    success: function (res) {
      if (res.confirm) {
        messages.value = [];
        // 自动发送欢迎消息
        nextTick(() => {
          autoSendWelcomeMessage();
        });
      }
    }
  });
};

// 切换到语音输入
const switchToVoice = () => {
  uni.showToast({
    title: '语音输入功能开发中',
    icon: 'none'
  });
};

// 选择图片
const chooseImage = () => {
  uni.showToast({
    title: '图片识别功能开发中',
    icon: 'none'
  });
};

// 显示健康菜单
const showHealthMenu = () => {
  uni.showToast({
    title: '健康菜单功能开发中',
    icon: 'none'
  });
};

// 处理输入框聚焦
const handleInputFocus = () => {
  // 在输入框聚焦时滚动到底部
  scrollToBottom();
};

// 处理输入框失焦
const handleInputBlur = () => {
  // 可以在这里处理一些失焦事件
};
</script>

<style lang="scss">
page {
  background-color: #f7f9fc;
  height: 100%;
}

.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  
  .header {
    background: linear-gradient(135deg, #8fd3f4, #84fab0);
    padding: 15px 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    
    .page-title {
      font-size: 18px;
      font-weight: bold;
      color: #fff;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    
    .header-right {
      position: absolute;
      right: 15px;
      
      .reset-btn {
        font-size: 22px;
        color: #fff;
        padding: 5px;
      }
    }
  }
  
  .chat-container {
    flex: 1;
    padding: 15px;
    box-sizing: border-box;
    
    .welcome-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30px 20px;
      
      .ai-logo {
        width: 120px;
        height: 120px;
        border-radius: 60px;
        margin-bottom: 20px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        border: 4px solid #fff;
      }
      
      .welcome-title {
        font-size: 22px;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
      }
      
      .welcome-desc {
        font-size: 14px;
        color: #666;
        text-align: center;
        margin-bottom: 30px;
        line-height: 1.5;
      }
      
      .suggest-questions {
        width: 100%;
        
        .question-item {
          background-color: #fff;
          padding: 12px 15px;
          border-radius: 15px;
          margin-bottom: 10px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          border: 1px solid #eaeaea;
          
          .question-text {
            font-size: 14px;
            color: #555;
          }
          
          &:active {
            background-color: #f0f7ff;
          }
        }
      }
    }
    
    .message-list {
      width: 100%;
      
      .message-item {
        display: flex;
        margin-bottom: 20px;
        
        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          background-color: #f0f0f0;
          flex-shrink: 0;
        }
        
        .message-bubble {
          max-width: 70%;
          padding: 12px 15px;
          border-radius: 18px;
          position: relative;
          word-break: break-word;
          
          .message-text {
            font-size: 15px;
            line-height: 1.5;
          }
          
          .message-time {
            font-size: 10px;
            color: #999;
            margin-top: 5px;
            text-align: right;
          }
        }
        
        &.user-message {
          flex-direction: row-reverse;
          
          .user-avatar {
            margin-left: 10px;
          }
          
          .user-bubble {
            background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
            color: #333;
            margin-right: 10px;
            border-bottom-right-radius: 4px;
          }
        }
        
        &.ai-message {
          .ai-avatar {
            margin-right: 10px;
            border: 2px solid #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }
          
          .ai-bubble {
            background-color: #fff;
            color: #333;
            margin-left: 10px;
            border-bottom-left-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          }
        }
      }
      
      .ai-typing {
        display: flex;
        margin-bottom: 20px;
        
        .ai-avatar {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          margin-right: 10px;
          border: 2px solid #fff;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .typing-bubble {
          background-color: #fff;
          padding: 15px;
          border-radius: 18px;
          border-bottom-left-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          
          .typing-dots {
            display: flex;
            align-items: center;
            
            .dot {
              width: 8px;
              height: 8px;
              border-radius: 4px;
              background-color: #ccc;
              margin-right: 4px;
              animation: typing-animation 1.5s infinite ease-in-out;
              
              &:nth-child(1) {
                animation-delay: 0s;
              }
              
              &:nth-child(2) {
                animation-delay: 0.3s;
              }
              
              &:nth-child(3) {
                animation-delay: 0.6s;
                margin-right: 0;
              }
            }
          }
        }
      }
    }
  }
  
  .input-area {
    padding: 10px 15px 15px;
    background-color: #fff;
    border-top: 1px solid #f0f0f0;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    
    .input-wrapper {
      display: flex;
      align-items: flex-end;
      background-color: #f5f7fa;
      border-radius: 20px;
      padding: 8px 12px;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
      
      .message-input {
        flex: 1;
        font-size: 15px;
        min-height: 20px;
        max-height: 100px;
        padding: 5px 0;
        color: #333;
      }
      
      .send-btn {
        width: 34px;
        height: 34px;
        border-radius: 17px;
        background-color: #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 8px;
        flex-shrink: 0;
        transition: all 0.3s ease;
        
        .send-icon {
          font-size: 18px;
          color: #fff;
        }
        
        &.active {
          background: linear-gradient(135deg, #8fd3f4, #84fab0);
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
          
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
    
    .function-bar {
      display: flex;
      margin-top: 10px;
      justify-content: space-around;
      
      .function-item {
        width: 50px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .iconfont {
          font-size: 24px;
          color: #8fd3f4;
        }
        
        &:active {
          opacity: 0.7;
        }
      }
    }
  }
}

@keyframes typing-animation {
  0% {
    transform: translateY(0);
    background-color: #ccc;
  }
  
  50% {
    transform: translateY(-5px);
    background-color: #8fd3f4;
  }
  
  100% {
    transform: translateY(0);
    background-color: #ccc;
  }
}
</style> 